package com.mall.users.interceptor;

import com.mall.commons.utils.Constants;
import com.mall.commons.utils.JwtUtils;
import com.mall.model.domain.UmsAdmin;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Token拦截器
 */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到请求: {}",request.getRequestURI());
        String token = request.getHeader(Constants.TOKEN_AUTHORIZATION);
        token = token.replaceAll(Constants.TOKEN_PREFIX, "");
        log.info(token);
        Claims claims = JwtUtils.getClaims(token);
        String username = claims.get("username",String.class);
        Long id =claims.get("id",Long.class);
        UmsAdmin umsAdmin = new UmsAdmin();
        umsAdmin.setId(id);
        umsAdmin.setUsername(username);
        //存进UmsAdminHolder
        UmsAdminHolder.set(umsAdmin);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UmsAdminHolder.remove();
    }
}
